const db = require('../db')
const jwt = require('jsonwebtoken')
const config = require('../config')
exports.regUser = (req, res) => {
  res.send('reguser OK')
}
// 登录的处理函数
exports.alogin = (req, res) => {
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  const userinfo = req.body
  const str1 = 'select * from auser where username = ?'
  db.query(str1, userinfo.username, (err, results) => {
    if (err) return res.cc(err)
    // 执行 SQL 语句成功，但是查询到数据条数不等于 1
    if (results.length !== 1) return res.cc('用户名不存在，登录失败！')
    // 该判断密码,密码加密了，需要解密
    if (results[0].password != userinfo.password)
      return res.cc('密码错误，登录失败')
    // 这样不对，因为user info里面有密码，用户头像，剔除
    // const tokenstr = jwt.sign(userinfo, config.jwtSecretKey, { expiresIn: config.expiresIn })
    // , user_pic: ''
    const user = { ...results[0], password: '' }
    const tokenstr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    })
    res.send({
      status: 0,
      message: '登录成功！',
      success: true,
      data: {
        token: 'Bearer ' + tokenstr,
      },
    })
  })
}
